<template>



  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="80%" @ok="handleSubmit">
    <vxe-grid ref="tableRef" v-bind="gridOptions" :style="{height: (contentHeight*0.9)+'px'}">
      <template #toolbar_buttons>
        <!--            <Button type="primary" size="small" @click="addFn">添加题目</Button>-->
        {{dataList?.categoryName}}
      </template>
      <template #action="{ row }">
        <TableAction outside :actions="getActions(row)" />
      </template>

    </vxe-grid>
  </BasicDrawer>
</template>
<script lang="ts" setup>

/**
 * 选择试题题目
 */

import { BasicTable, useTable, TableAction } from '@/components/Table';
import { ref, computed, unref, h, toRaw, reactive } from 'vue';
import { Button } from 'ant-design-vue';
import { BasicForm, useForm, ApiTreeSelect } from '@/components/Form';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { useDrawer } from '@/components/Drawer';

import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
  VxeTableDefines,
} from '@/components/VxeTable';

import {
  titleGroupform,
  titleGroupColumns,
  chooseQuestionColumns
} from './role.data';

import { BasicModal, useModalInner } from '@/components/Modal';
import { Form, FormItem, Input, InputNumber, DatePicker, Select, Switch } from 'ant-design-vue';
import SelectQuestionDrawer from '@/views/components/ex/SelectQuestionDrawer/SelectQuestionDrawer.vue';

import { countByCategoryId, categoryList } from '@/api/heng/ex';


import { useMessage } from "@/hooks/web/useMessage";
import util from '@/utils/util';

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const { createMessage } = useMessage();

const chooseQuestion = useDrawer();

const id = ref("")



const tableRef = ref();

const dataList = ref({});
const countNum = ref(0);
const contentHeight = ref(window.innerHeight);


const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: chooseQuestionColumns,
  filterConfig: {
    remote: true,
  },
  treeConfig: {
    rowField: 'type',
    childrenField: 'options',
    expandAll: true
  },
  expandConfig: {},

  showFooter: true,
  footerData: [
    { title: '合计' }
  ],
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    // enabled: true,
  },
  pagerConfig: {
    // pageSize: 20,
  },
  proxyConfig: {
    enabled: false,
  },
});




const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  //打开弹层后的回调
  // resetFields();
  setDrawerProps({ confirmLoading: false });
  console.log("---data:",data)
  dataList.value = data;
  count.value=data.questions?.length;
  // id.value = data.paperGroupId;
  tableRef.value.reloadData(data.questions);
  gridOptions.footerData[0].title = "共" + data.questions.length + "条";


});

const getTitle = computed(() => ('查看分类题目'));


//async function handleSubmit()

async function handleSubmit() {
  try {
    // console.log("--dataList.value:",dataList.value)
    // emit('success', values);
    closeDrawer();

  } catch (e) {
    console.log(e)
  } finally {
    setDrawerProps({ confirmLoading: false });

  }
}

function sunccFn(result) {
  if (result && result.code == 200) {
    createMessage.success(result.message);
  } else {
    createMessage.error(result.message);
  }
  closeDrawer()
  emit('success');
}

function cancelFn() {
  //  tableRef.value.clearValidate();
}


function getActions(record) {
  let arr = [
    {
      // icon: 'ant-design:delete-outlined',
      label: '删除',
      color: 'error',
      onClick: handleClose.bind(null, record)
      // popConfirm: {
      //   title: '是否删除？',
      //   placement: 'left',
      //   confirm: handleClose.bind(null, record),
      // },
    }
  ];


  return arr;
}

const count = ref(0);
const addNum = ref(0);

function handleClose(record: Recordable) {

  tableRef.value.remove(record);
  addNum.value = addNum.value - 1;
  countTableNum()
}


function countTableNum() {
  // let t_list = tableRef.value.getTableData();
  // console.log("----countTableNum:", t_list);

}


async function countByCategoryIdFn() {
  const values = await validate();
  countByCategoryId({ categoryId: values.categoryId }).then(res => {
    //console.log("----countByCategoryIdFn:", res);
    if (res.code == 200) {
      count.value = res.data;
    }
  });

}

async function addFn() {
  const values = await validate();
  //console.log("--addFn-values:", values);
  // tableRef.value.insertAt({ questionId: id.value, isTrue: 0 }, -1);
  let t_list = tableRef.value.getTableData().tableData;
  t_list.forEach(item => {
    item.isChecked = true;
  })
  values.select_list=t_list;
  chooseQuestion[1].openDrawer(true, values)
}


function handleSuccess(list) {
  list.forEach((item) => {
    item.createTime=null;
  })
  addNum.value = addNum.value + list.length;
  // console.log("----c:", list);
  tableRef.value.insert(list);
  countTableNum();
}


function handleFieldValueChange(e) {
  console.log("---handleFieldValueChange:", e);
  if (e == 'type') {
    countByCategoryIdFn();
  }
}

function handleTreeChange(e1, e2, model, field) {
  // console.log("---handleTreeChange:", e1, e2);
  let categoryName = e2[0];
  model.categoryName = categoryName;
}




</script>
<style lang="less">
.item-row {
  margin: 0 auto;

  //padding-left: 5%;
  .ant-form-item-label {
    flex: 0 0 28.5%;
    max-width: 28.5%;
  }
}

.lqfp-8 {
  //padding-left: 9% !important;

}
</style>
